package com.test.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebFilter("/*")
public class LoginFilter implements Filter {

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpSession session = req.getSession();
		// URL地址
		String method = req.getRequestURI();
		if (method != null && (method.contains("login") || method.contains("login2") || method.contains("register") || method.contains("imageServlet"))) {
			chain.doFilter(request, response);
			return;
		}

		String username = (String) session.getAttribute("username");
		Integer number = (Integer)session.getAttribute("number");
		if (username != null || number != null) {

			chain.doFilter(request, response);
		} else { // 没有登录，中转到登录页面
			System.out.println("请登录帐号!!!!!!!!!!");
			if( username == null || number == null) {
				((HttpServletResponse) response).sendRedirect("login.jsp");
			}
		
		}
	}

	public void init(FilterConfig fConfig) throws ServletException {
	}

}
